import { Injectable, Inject } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Project, User } from '../domain';
import { Observable } from 'rxjs/Observable';
import * as _ from 'lodash';

@Injectable()
export class ProjectService {
  // 定义api路径
  private readonly domain = 'projects';
  private headers = new HttpHeaders({ 'Content-Type': 'application/json' });
  constructor(
    @Inject('BASE_CONFIG') private config,
    private http: HttpClient) { }

  /**
   * 添加项目
   * @param project
   */
  add(project: Project): Observable<Project> {
    project.id = null;
    const uri = `${this.config.uri}/${this.domain}`;
    return this.http
      .post<Project>(uri, JSON.stringify(project), { headers: this.headers });
  }
  /**
   * 修改项目
   * @param project
   */
  update(project: Project): Observable<Project> {
    const uri = `${this.config.uri}/${this.domain}/${project.id}`;
    const toUpdate = {
      name: project.name,
      desc: project.desc,
      coverImg: project.coverImg
    };
    return this.http
      // 指定修改的选项
      .patch<Project>(uri, JSON.stringify(toUpdate), { headers: this.headers });
  }

  /**
   * 删除项目
   * @param project
   */
  del(project: Project): Observable<Project> {
    const delTask$ = Observable.from(project.taskLists || []) // 从 项目中获取 taskList 的所有流
      // 同时进行 先删除project 项目下的任务
      .mergeMap(listId => this.http.delete(`${this.config.uri}/taskLists/${listId}`))
      // 获取完成序列的总数
      .count();
    return delTask$.switchMap(_ => this.http.delete(`${this.config.uri}/${this.domain}/${project.id}`))
      // 返回删除的对象
      .mapTo(project);
  }

  get(userId: string): Observable<Project[]> {
    const uri = `${this.config.uri}/${this.domain}`;
    return this.http
      .get<Project[]>(uri, { params: { 'members_like': userId } });
  }

  // 邀请成员
  invite(projectId, users: User[]): Observable<Project> {
    const uri = `${this.config.uri}/${this.domain}/${projectId}`;
    return this.http.get<Project>(uri)
      .switchMap(project => {
        const existingMembers = project.members;
        const inviteIds = users.map(user => user.id);
        const newIds = _.union(existingMembers, inviteIds);
        return this.http.patch<Project>(uri, JSON.stringify({ members: newIds }), { headers: this.headers });
      });
  }
}
